<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle" />
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!--      <crudOperation :permission="permission" />-->
      <!--表单组件-->
      <el-dialog
        :show-close="false"
        :before-close="crud.cancelCU"
        :visible.sync="dialogFormVisible"
        :title="crud.status.title"
        width="700px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small">
          <el-form-item label="医生" prop="doctorId">
            <el-select
              v-model="form.doctorDatas"
              filterable
              style="width: 437px"
              multiple
              placeholder="请选择"
              default-first-option
              @remove-tag="deleteDoctor"
              @change="changeDoctor"
            >
              <el-option
                v-for="item in doctors"
                :key="item.nickName"
                filterable
                :label="item.nickName"
                :value="item.doctorId"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.isMorning" label="上午值班时间">
            <el-time-select
              v-model="form.morningStartTime"
              :picker-options="{
                start: '06:00',
                step: '00:30',
                end: '12:00'
              }"
              placeholder="上午开始小时"
            />
            <el-time-select
              v-model="form.morningEndTime"
              :picker-options="{
                start: '6:00',
                step: '00:30',
                end: '12:00'
              }"
              placeholder="上午结束小时"
            />
          </el-form-item>
          <el-form-item v-if="form.isAfternoon" label="下午值班时间">
            <el-time-select
              v-model="form.afternoonStartTime"
              :picker-options="{
                start: '12:00',
                step: '00:30',
                end: '18:00'
              }"
              placeholder="下午开始小时"
            />
            <el-time-select
              v-model="form.afternoonEndTime"
              arrow-control
              :picker-options="{
                start: '12:00',
                step: '00:30',
                end: '18:00'
              }"
              placeholder="下午结束小时"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="close">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="add()">确认</el-button>
        </div>
      </el-dialog>

      <div style="text-align: left;display: flex;align-items: center">
        <H2>排班表</H2>
        <el-date-picker
          v-model="selectedDate"
          :clearable="false"
          class="ml-5"
          style="margin-left: 15px"
          type="month"
          value-format="yyyy-MM"
          format="yyyy-MM"
          placeholder="请选择月份"
          @change="dateChangeHandler"
        />
        <!--        <el-button :disabled="list.length > 0" style="margin-left: 5px" type="primary" @click="generateSchedule">自动生成排班表</el-button>-->
        <!--        <el-popconfirm-->
        <!--          class="ml-5"-->
        <!--          confirm-button-text="确定"-->
        <!--          cancel-button-text="我再想想"-->
        <!--          icon="el-icon-info"-->
        <!--          icon-color="red"-->
        <!--          :title="'确定删除' + selectedDate + '月值班表吗？'"-->
        <!--          @confirm="deleteSchedule"-->
        <!--        >-->
        <!--          <el-button slot="reference" type="danger">删除值班表 <i class="el-icon-remove-outline" /></el-button>-->
        <!--        </el-popconfirm>-->
      </div>
      <el-calendar v-model="selectedDate">
        <template slot="dateCell" slot-scope="{date, data}">
          <div style="display: flex;justify-content: center">
            <div style="width: 100%;display: flex;justify-content: center">
              <div style="margin-right: 5px">
                {{ data.day.split('-').slice(1).join('-') }}
              </div>
            </div>
          </div>
          <template v-if="data && list==0">
            <div v-for="(item,index) in days" :key="index" style="width:100%;display: flex;flex-direction: column;align-items: center">
              <!-- 先渲染上午和下午 -->
              <el-tag v-if="item.schedule_date === data.day" class="atHover" style="margin-top: 6px" @click="editDialogOpenHandler(item,true)">
                上午<i class="el-icon-edit" />
              </el-tag>
              <el-tag v-if="item.schedule_date === data.day" class="atHover" style="margin-top: 10px" @click="editDialogOpenHandler(item,false)">下午<i class="el-icon-edit" /></el-tag>
              <!-- 最后渲染夜班 -->
              <!--            <el-tag @click="editDialogOpenHandler(item)" class="atHover" style="margin-top: 10px" :type="item.dayTypeId === 6 &&item.shiftId === 3 ? 'danger' :(item.dayTypeId>1 && item.dayTypeId < 6) ? 'primary' : 'danger' " v-if="item.date === data.day && item.shiftId === 3">夜班<i class="el-icon-edit"></i></el-tag>-->
            </div>
          </template>
          <template v-else>
            <div v-for="(item,index) in list" :key="index" style="width:100%;display: flex;flex-direction: column;align-items: center">
              <!-- 先渲染上午和下午 -->
              <el-tag v-if="item.scheduleDate === data.day && item.isMorning" class="atHover" style="margin-top: 6px" @click="editDialogOpenHandler(item)">
                上午:{{ item.nickName }}<i class="el-icon-edit" />
              </el-tag>
              <el-tag v-if="item.scheduleDate === data.day && item.isAfternoon" class="atHover" style="margin-top: 10px" @click="editDialogOpenHandler(item)">下午:{{ item.nickName }}<i class="el-icon-edit" /></el-tag>
              <!-- 最后渲染夜班 -->
              <!--            <el-tag @click="editDialogOpenHandler(item)" class="atHover" style="margin-top: 10px" :type="item.dayTypeId === 6 &&item.shiftId === 3 ? 'danger' :(item.dayTypeId>1 && item.dayTypeId < 6) ? 'primary' : 'danger' " v-if="item.date === data.day && item.shiftId === 3">夜班<i class="el-icon-edit"></i></el-tag>-->
            </div>
          </template>
        </template>
      </el-calendar>
      <!--分页组件-->
      <!--      <pagination />-->
    </div>
  </div>
</template>

<script>
import crudDoctorSchedule, { getCurrentAll, add } from '@/api/system/doctorSchedule'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'
import { getAllDoctor } from '@/api/system/sysDoctor'
import dayjs from 'dayjs'

let userDoctor = []
const defaultForm = {
  scheduleId: null,
  doctorId: null,
  isAllDay: null,
  morningStartTime: null,
  morningEndTime: null,
  afternoonStartTime: null,
  afternoonEndTime: null,
  intervalMinutes: null,
  createTime: null,
  updateTime: null,
  isAfternoon: false,
  isMorning: false
}
export default {
  name: 'DoctorSchedule',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '排班',
      url: 'api/doctorSchedule',
      idField: 'scheduleId',
      sort: 'scheduleId,desc',
      crudMethod: { ...crudDoctorSchedule }

    })
  },
  data() {
    return {
      days: [],
      selectedDate: dayjs().format('YYYY-MM'),
      list: [],
      doctor: [],
      doctors: [],
      // 多选的时候使用
      doctorDatas: [],
      dialogFormVisible: false,
      permission: {
        add: ['admin', 'doctorSchedule:add'],
        edit: ['admin', 'doctorSchedule:edit'],
        del: ['admin', 'doctorSchedule:del']
      },
      rules: {
        isAllDay: [
          { required: true, message: '是否全天（1: 是, 0: 否）不能为空', trigger: 'blur' }
        ],
        intervalMinutes: [
          { required: true, message: '排班时间间隔（分钟）不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'dayOfWeek', display_name: '星期几（MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY）' },
        { key: 'isAllDay', display_name: '是否全天（1: 是, 0: 否）' }
      ]
    }
  },
  methods: {
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.doctors = []
      this.doctor = []
      this.doctorDatas = []
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      console.log(crud)
      console.log(form)
      // form = null
      this.form.doctorDatas = []
      this.form.doctorDatas.push(form.doctorId)
      // this.getDoctors()
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      // this.getDoctors()
      this.load()
      return false
    },
    // 获取弹窗里面的医生数据
    getDoctors() {
      getAllDoctor().then(res => {
        this.doctors = res
      }).catch(() => {
      })
    },
    // 选择医生
    changeDoctor(value) {
      userDoctor = []
      value.forEach(function(data, index) {
        const doctor = { id: data }
        defaultForm.doctorId = data
        userDoctor.push(doctor)
      })
    },
    // 删除医生
    deleteDoctor(value) {
      userDoctor.forEach(function(data, index) {
        if (data.id === value) {
          userDoctor.splice(index, value)
        }
      })
    },
    dateChangeHandler() {
      this.load()
    },
    deleteSchedule() {
      // this.request.delete("/schedule/deleteSchedule/"+this.selectedDate).then(res => {
      //   if(res.code === '0'){
      //     this.$message.success("删除成功")
      //     this.load()
      //   }else {
      //     this.$message.error("删除失败")
      //   }
      // })
    },
    // 生成排班
    generateSchedule() {
      this.loading = true
      // this.request.get("/schedule/generateSchedule",{
      //   params:{
      //     date:this.selectedDate
      //   }
      // }).then(res => {
      //   if(res.code === '0'){
      //     this.$message.success("生成成功")
      //     const shift1 = this.list.filter(item => item.shiftId === 1)
      //     const shift2 = this.list.filter(item => item.shiftId === 2)
      //     const shift3 = this.list.filter(item => item.shiftId === 3)
      //     this.list = shift1.concat(shift2).concat(shift3)
      //     this.load()
      //     this.loading = false
      //
      //   }else {
      //     this.$message.error("生成失败")
      //     this.loading = false
      //   }
      // })
    },
    editDialogOpenHandler(item, isMorning) {
      this.form = JSON.parse(JSON.stringify(item))
      this.getDoctors()
      this.form.intervalMinutes = 5
      if (isMorning) {
        // 如果是早上
        this.form.isMorning = true
      } else {
        // 如果是下午
        this.form.isAfternoon = true
      }
      this.form.doctorDatas = []
      this.form.doctorDatas.push(item.doctorId)
      this.dialogFormVisible = true
    },
    load() {
      return new Promise((resolve, reject) => {
        getCurrentAll(this.selectedDate)
          .then(res => {
            if (res != null && res.length > 0) {
              this.list = res
              // const shift1 = this.list.filter(item => item.shiftId === 1)
              // const shift2 = this.list.filter(item => item.shiftId === 2)
              // const shift3 = this.list.filter(item => item.shiftId === 3)
              // this.list = shift1.concat(shift2).concat(shift3)
              resolve()
            } else {
              this.generateDays(this.selectedDate)
              // 获取yyyy-mm下的所有dd，然后放到list
              // this.request.get('/api/doctorSchedule/getAllDay', {
              //   params: {
              //     date: this.selectedDate
              //   }
              // }).then(res => {
              //   if (res.data.length > 0) {
              //     this.list = res.data
              //     const shift1 = this.list.filter(item => item.shiftId === 1)
              //     const shift2 = this.list.filter(item => item.shiftId === 2)
              //     const shift3 = this.list.filter(item => item.shiftId === 3)
              //     this.list = shift1.concat(shift2).concat(shift3)
              //     resolve()
              // }
              // this.list = []
              this.$message.error('当前没有排班信息，请先排班')
              resolve()
            }
          }).catch(res => {
            reject(res)
          })
      })
    },
    // 接收 yyyy-mm 格式的字符串，生成该月份的所有日期
    generateDays(yearMonth) {
      const [year, month] = yearMonth.split('-').map(Number)
      const daysInMonth = new Date(year, month + 1, 0).getDate()

      // 创建新的days数组以确保Vue检测到变化
      const newDays = Array.from({ length: daysInMonth }, (_, i) => ({
        schedule_date: `${year}-${String(month).padStart(2, '0')}-${String(i + 1).padStart(2, '0')}`
      }))

      // 使用 this.$set 或直接替换整个数组来触发视图更新
      // 方案一：直接替换整个数组
      this.days = newDays

      // 方案二：使用 this.$set（如果需要逐个添加）
      // this.days.length = 0; // 清空原有数组
      // newDays.forEach(day => {
      //   this.$set(this.days, this.days.length, day);
      // });
    },
    close() {
      this.dialogFormVisible = false
    },
    add() {
      add(this.form).then(res => {
        console.log(res)
      })
    },
    test(row) {
      console.log(row)
    }
  }
}
</script>

<style scoped>
/deep/ .el-calendar-day  {
  box-sizing: border-box;
  padding: 5px;
  height: 140px;
}
/deep/ .el-button-group{
  display: none;
}
.atHover:hover{
  transform: scale(1.2);
}

</style>
